package com.learn.authentication.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.learn.authentication.mapper.UserMapper;
import com.learn.authentication.pojo.User;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.time.Instant;
import java.time.ZonedDateTime;
import java.time.temporal.ChronoUnit;

/**
 * @author DJJ_F
 * @version 1.0
 * @date 2025/04/06
 * @description
 */
@Component
@Slf4j
public class JwtUtil {
    @Autowired
    private UserMapper userMapper;

    private static UserMapper staticUserMapper;

    // 表示该方法在类实例化之后（通过构造函数创建对象之后）立即执行
    @PostConstruct
    public void setUserMapper() {
        staticUserMapper = userMapper;
    }


    /**
     * 根据用户id和密码生成token
     * @param userId
     * @param pwd
     * @return String
     */
    public static String genToken(String userId, String pwd) {

        return JWT.create()
                .withAudience(userId)
                // 添加周就报错了
                .withExpiresAt(Instant.now().plus(7, ChronoUnit.DAYS))
//                .withExpiresAt(ZonedDateTime.now().plusWeeks(1).toInstant())
                .sign(Algorithm.HMAC256(pwd));
    }

    /**
     * 根据请求头的token解析生成user对象
     * @return user
     */
    public static User getCurrentUser() {
        User user = null;
        try {
            String userId = getCurrentUserId();
            user = staticUserMapper.selectById(Integer.parseInt(userId));
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return user;
    }
    public static String getCurrentUserId() {
        String userId;
        try {
            String token = ((ServletRequestAttributes)
                    RequestContextHolder.getRequestAttributes())
                    .getRequest().getHeader("token");
            userId = JWT.decode(token).getAudience().get(0);
        } catch (Exception e) {
            log.error(e.getMessage());
            throw e;
        }
        return userId;
    }
    public static String getCurrentUserId(String token) {
        String userId;
        try {
            userId = JWT.decode(token).getAudience().get(0);
        } catch (Exception e) {
            log.error(e.getMessage());
            throw e;
        }
        return userId;
    }
}
